package com.kfm.web.servlet;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kfm.web.mapper.IUserMapper;
import com.kfm.web.model.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/user")
public class UserServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String num = req.getParameter("num");

        SqlSessionFactory factory = (SqlSessionFactory) getServletContext().getAttribute("factory");
        SqlSession sqlSession = factory.openSession();
        IUserMapper mapper = sqlSession.getMapper(IUserMapper.class);

        if (num == null || "".equals(num)) {
            num = "1";
        }
        PageHelper.startPage(Integer.parseInt(num), 10);

        List<User> users = mapper.selectAll();

        PageInfo<User> userPageInfo = new PageInfo<>(users);

        req.setAttribute("users", userPageInfo);
        // 到页面
        req.getRequestDispatcher("/WEB-INF/user.jsp").forward(req, resp);
    }
}
